package cn.ilikes.tools.nosql.jpa.clients.admins;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.slf4j.Logger;

import cn.ilikes.tools.logs.Loggerfactory;
import cn.ilikes.tools.nosql.jpa.JPASQLPersistenUnitEnv;
import cn.ilikes.tools.nosql.jpa.SysConfigs;
import cn.ilikes.tools.nosql.jpa.configs.databases.DataStoreConfigs;

/**
 * 
 * @author fack
 * 
 */
public class JPAHbaseAdmin extends AbAdminImple implements IAdmin<HBaseAdmin> {

	private Logger logger = Loggerfactory.instance(JPAHbaseAdmin.class);

	private HBaseAdmin hBaseAdmin;

	private boolean init = false;

	private boolean isInit() {
		return init;
	}

	private void setInit(boolean init) {
		this.init = init;
	}

	public JPAHbaseAdmin(JPASQLPersistenUnitEnv persistenUnitEnv) {
		super(persistenUnitEnv);
	}

	@Override
	public void init() {
		try {
			Loggerfactory.info(logger, "JPA Hbase Admin  Start init ... ");
			DataStoreConfigs dataStoreConfigs = getHbasePersistenUnitEnv().getPersistenceUnitMetadata().getDataStore();
			String node = dataStoreConfigs.getConnection().getProperties().getProperty(SysConfigs.hbase_datasore_master_node);
			String port = dataStoreConfigs.getConnection().getProperties().getProperty(SysConfigs.hbase_datasore_master_port);
			Configuration hadoopConf = new Configuration();
			hadoopConf.set("hbase.master", node + ":" + port);
			Loggerfactory.info(logger, "hbase.master : " + node + ":" + port);
			HBaseAdmin hbaseAdmin = new HBaseAdmin(hadoopConf);
			setInit(true);
			sethBaseAdmin(hbaseAdmin);
		} catch (MasterNotRunningException e) {
			throw new JPAAdminRunTimeException(e);
		} catch (ZooKeeperConnectionException e) {
			throw new JPAAdminRunTimeException(e);
		}

	}

	private void sethBaseAdmin(HBaseAdmin hBaseAdmin) {
		this.hBaseAdmin = hBaseAdmin;
	}

	@Override
	public HBaseAdmin getAdmin() {
		checkInit();
		return hBaseAdmin;
	}

	public void checkInit() {
		boolean init = isInit();
		if (!init)
			throw new JPAAdminRunTimeException("JPA Hbase Admin Not init ... ");
	}

	@Override
	public void close() {
		if (hBaseAdmin != null)
			try {
				Loggerfactory.info(logger, "HBase Admin  Close ");
				hBaseAdmin.close();
			} catch (IOException e) {
				Loggerfactory.warn(logger, e.getMessage());
			}

	}
}
